﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SyncUdp.UI
{
    using DG.Tweening;
    using SyncUdp.Event.GameEvent;
    using SyncUdp.Interface;
    using UnityEngine.UI;
    using static Unity.IO.LowLevel.Unsafe.AsyncReadManagerMetrics;

    /// <summary>
    /// 主菜单 UI
    /// </summary>
    public class MainMenuUIController : AbstractMonoSingleton, IUIController
    {
        #region UI 字段
        [Header("主菜单相关 UI")]
        [SerializeField, Tooltip("创建游戏的按钮")]
        Button _createGameButton;

        [SerializeField, Tooltip("加入游戏的按钮")]
        Button _joinGameButton;

        [SerializeField, Tooltip("退出的按钮")]
        Button _quitButton;

        [Header("创建游戏相关 UI")]
        [SerializeField, Tooltip("创建游戏面板")]
        GameObject _createGamePanel;

        [SerializeField, Tooltip("IP 地址输入")]
        InputField _ipAddressInput;

        [SerializeField, Tooltip("端口号输入")]
        InputField _portInput;

        [SerializeField, Tooltip("最大玩家数量输入")]
        InputField _maxPlayerCountInput;

        [SerializeField, Tooltip("名字输入")]
        InputField _playerNameInput;

        [SerializeField, Tooltip("确定按钮")]
        Button _ensureButton;

        [SerializeField, Tooltip("关闭面板按钮")]
        Button _closePanelButton;

        [SerializeField, Tooltip("提示文本，用于显示错误")]
        Text _tipText;
        #endregion

        Coroutine _showTipCoroutine;

        public string IPAddressStr { get => _ipAddressInput.text; }

        public string PortStr { get => _portInput.text; }

        public string MaxPlayerCountStr { get => _maxPlayerCountInput.text; }

        public string PlayerNameStr { get => _playerNameInput.text; }

        protected override void InitOnStart()
        {
            _createGameButton.onClick.AddListener(OnCreateGameBtnClicked);
            _joinGameButton.onClick.AddListener(OnJoinGameBtnClicked);
            _quitButton.onClick.AddListener(OnQuitBtnClicked);
            _closePanelButton.onClick.AddListener(() => _createGamePanel.gameObject.SetActive(false));
        }

        /// <summary>
        /// 显示提示文本
        /// </summary>
        /// <param name="msg"></param>
        void ShowTip(string msg)
        {
            if (_showTipCoroutine != null)
                StopCoroutine(_showTipCoroutine);
            _showTipCoroutine = StartCoroutine(ShowTipCoroutine(msg, 1f));
        }

        /// <summary>
        /// 使创建游戏面板的两个按钮是否能够交互
        /// </summary>
        /// <param name="canInteractable"></param>
        void ActivateButtonsOnPanel(bool canInteractable)
        {
            _ensureButton.interactable = canInteractable;
            _closePanelButton.interactable = canInteractable;
        }

        #region 协程
        IEnumerator ShowTipCoroutine(string msg, float time)
        {
            _tipText.color = Color.red;
            _tipText.text = msg;
            yield return new WaitForSeconds(time);
            var targetColor = new Color(0, 0, 0, 0);
            float t = 0;
            // 指定时间（秒为单位）内变透明
            while (gameObject.activeSelf && _createGamePanel.activeSelf && t < time)
            {
                _tipText.color = Color.Lerp(_tipText.color, targetColor, t / time);
                t += Time.deltaTime;
                yield return null;
            }
            // 确保为透明的
            _tipText.color = targetColor;
            _showTipCoroutine = null;
        }

        IEnumerator WaitingToJoinGameCoroutine()
        {
            bool flag = false, isSuccessful = false;
            string tip2Show = string.Empty;
            _gm.JoinGame((successful, tip) =>
            {
                flag = true;
                isSuccessful = successful;
                tip2Show = tip;
            });
            while (flag == false)
                yield return null;
            if (isSuccessful == false)
                ShowTip(tip2Show);                
            ActivateButtonsOnPanel(true);
        }
        #endregion

        #region 方法实现
        public void Show()
        {
            gameObject.SetActive(true);
            _createGamePanel.SetActive(false);
            _tipText.color = new Color(0, 0, 0, 0);
        }

        public void Hide()
        {
            gameObject.SetActive(false);
            ActivateButtonsOnPanel(true);
        }
        #endregion

        #region 回调方法
        void OnCreateGameBtnClicked()
        {
            _ensureButton.onClick.RemoveAllListeners();
            _ensureButton.onClick.AddListener(EnsureThatCreatGame);
            _createGamePanel.SetActive(true);
            _maxPlayerCountInput.transform.parent.gameObject.SetActive(true);
        }

        void OnJoinGameBtnClicked()
        {
            _ensureButton.onClick.RemoveAllListeners();
            _ensureButton.onClick.AddListener(EnsureThatJoinGame);
            _createGamePanel.SetActive(true);
            _maxPlayerCountInput.transform.parent.gameObject.SetActive(false);
        }

        void OnQuitBtnClicked()
        {
            _gm.Quit();
        }

        /// <summary>
        /// 确认创建游戏
        /// </summary>
        void EnsureThatCreatGame()
        {
            ActivateButtonsOnPanel(false);
            var tip = string.Empty;
            bool flag = _gm.CreateGame(ref tip);
            if (flag)
                SendEvent(new GameCreatedSuccessfullyEvent());
            else
                ShowTip(tip);
            ActivateButtonsOnPanel(true);
        }

        /// <summary>
        /// 确认加入游戏
        /// </summary>
        void EnsureThatJoinGame()
        {
            ActivateButtonsOnPanel(false);
            StartCoroutine(WaitingToJoinGameCoroutine());
        }
        #endregion
    }
}
